package com.zyf.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zyf.common.excption.YyghException;
import com.zyf.common.result.ResultCodeEnum;
import com.zyf.model.hosp.BookingRule;
import com.zyf.model.hosp.Department;
import com.zyf.model.hosp.Hospital;
import com.zyf.model.hosp.Schedule;
import com.zyf.repository.ScheduleRepository;
import com.zyf.service.DepartmentService;
import com.zyf.service.HospitalService;
import com.zyf.service.ScheduleService;
import com.zyf.vo.hosp.BookingScheduleRuleVo;
import com.zyf.vo.hosp.ScheduleOrderVo;
import com.zyf.vo.hosp.ScheduleQueryVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 医院排班的  service实现类
 *
 * @author zyf
 * @date 2021年05月08日 14:45
 */
@Service
public class ScheduleServiceImpl  implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private DepartmentService departmentService;

    /**
     * 上传医院排班信息Api
     *
     * @param paramMap 医院排班信息的Map集合
     * @author zyf
     * @date 2021/5/8 14:56
     */
    @Override
    public void saveSchedule(Map<String, Object> paramMap) {
        //paramMap 转换为Department 对象
        String map = JSONObject.toJSONString(paramMap);
        Schedule schedule = JSONObject.parseObject(map, Schedule.class);

        Schedule scheduleExist = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());

        if (scheduleExist != null) {
            schedule.setStatus(1)
                    .setIsDeleted(0)
                    .setUpdateTime(new Date());
            scheduleRepository.save(schedule);
        } else {
            schedule.setStatus(1)
                    .setIsDeleted(0)
                    .setUpdateTime(new Date())
                    .setCreateTime(new Date());
            scheduleRepository.save(schedule);
        }
    }

    /**
     * 分页查询医院排班信息Api
     *
     * @param page    当前页码
     * @param limit   页面展示的条数
     * @param queryVo 条件查询的VO对象
     * @return Page<com.zyf.model.hosp.Schedule>
     * @author zyf
     * @date 2021/5/8 15:31
     */
    @Override
    public Page<Schedule> findScheduleByPage(int page, int limit, ScheduleQueryVo queryVo) {
        //创建Pageable对象，设置当前页和每页记录数
        //0 是第一页
        Pageable pageable = PageRequest.of(page - 1, limit);

        //创建Examole对象
        Schedule schedule = new Schedule();
        if (queryVo != null) {
            BeanUtils.copyProperties(queryVo, schedule);
        }
        schedule.setStatus(1)
                .setIsDeleted(0);


        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Example<Schedule> example = Example.of(schedule, matcher);


        Page<Schedule> all = scheduleRepository.findAll(example, pageable);
        return all;
    }

    /**
     * 根据医院编号和排班编号删除医院排班API
     *
     * @param hoscode       医院编号
     * @param hosScheduleId 排班编号
     * @author zyf
     * @date 2021/5/8 15:36
     */
    @Override
    public void removeSchedule(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (schedule != null) {
            scheduleRepository.deleteById(schedule.getId());
        }
    }

    /**
     * 根据医院编号和科室编号，查询排班规则数据API
     * @author zyf
     * @date 2021/5/13 18:21
     * @param page 当前页
     * @param limit 页面显示记录数
     * @param hoscode 医院编号
     * @param depcode  科室编号
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    public Map<String, Object> getScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        Map<String, Object> map = new HashMap<>();

        //1、根据医院编号和科室编号查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        //2、根据工作日和workDate进行分组
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),//匹配条件
                Aggregation.group("workDate") //分组字段
                .first("workDate").as("workDate")
                //3、统计号源数量
                .count().as("docCount")
                .sum("reservedNumber").as("reservedNumber")
                .sum("availableNumber").as("availableNumber"),
                //排序
                Aggregation.sort(Sort.Direction.DESC,"workDate"),
                //4、实现分页
                Aggregation.skip((page-1)*limit),
                Aggregation.limit(limit)
        );

        //调用方法进行查询
        AggregationResults<BookingScheduleRuleVo> aggResult = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> mappedResults = aggResult.getMappedResults();

        //分组查询的总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> aggregate = mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);

        int total = aggregate.getMappedResults().size();

        //处理日期转换位为星期显示
        mappedResults.forEach(bookingScheduleRuleVo -> {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        });

        //根据医院编号获取医院名称
        String hospName =  hospitalService.getHospName(hoscode);
        HashMap<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname",hospName);


        //设置最终的数据，并返回
        map.put("scheduleList",mappedResults);
        map.put("total",total);
        map.put("baseMap",baseMap);

        return map;
    }

    /**
     * 根据医院编号、科室编号和工作日期，查询排班详细信息
     * @author zyf
     * @date 2021/5/14 14:13
     * @param hoscode 医院编号
     * @param depcode 科室编号
     * @param workDate  工作日期
     * @return java.util.List<com.zyf.model.hosp.Schedule>
     */
    @Override
    public List<Schedule> getScheduleDetail(String hoscode, String depcode, String workDate) {
        List<Schedule> scheduleList= scheduleRepository.getScheduleByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,new DateTime(workDate).toDate());

        //设置其他值  医院名称。科室名称，日期对应星期
        scheduleList.forEach(this::packageSchedule);
        return scheduleList;
    }


    /**
     * 获取可以预约的排班信息
     * @author zyf
     * @date 2021/5/28 18:22
     * @param page 当前页
     * @param limit 每页显示条数
     * @param hoscode 医院编号
     * @param depcode  科室编号
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        Map<String, Object> map = new HashMap<>();
        //根据医院编号获取预约规则
        Hospital hospital = hospitalService.getByHoscode(hoscode);
        if (hospital==null){
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        //获取可预约日期的数据，分页
        BookingRule bookingRule = hospital.getBookingRule();

        IPage iPage = this.getListDate(page,limit,bookingRule);

        //获取当前可预约的日期
        List<Date> dateList = iPage.getRecords();

        //获取可预约日期里面的科室的剩余记录数
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode).and("workDate").in(dateList);

        Aggregation agg  = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate").first("workDate").as("workDate").count().as("docCount")
                .sum("availableNumber").as("availableNumber")
                .sum("reservedNumber").as("reservedNumber")
        );

        AggregationResults<BookingScheduleRuleVo> results = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);

        List<BookingScheduleRuleVo> scheduleVoList = results.getMappedResults();

        //合并数据，map集合 key日期，value是预约规则和剩余数量等
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(scheduleVoList)){
            scheduleVoMap = scheduleVoList.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate,BookingScheduleRuleVo->BookingScheduleRuleVo));
        }

        //获取可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for (int i = 0,len = dateList.size(); i <len; i++) {
            Date date = dateList.get(i);
            //从map集合中根据key获取value
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            //如果说当前没有排班医生
            if(null == bookingScheduleRuleVo){
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //就诊医生数
                bookingScheduleRuleVo.setDocCount(0)
                        //科室剩余预约数  -1表示无号
                        .setAvailableNumber(-1);
            }
            bookingScheduleRuleVo.setWorkDate(date)
                    .setWorkDateMd(date);
            //计算当前日期为周几
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            //最后一页最后一条为即将预约， 状态0：正常  1：即将放号， -1当前已经停止挂号
            if(i==len-1 && page == iPage.getPages()){
                bookingScheduleRuleVo.setStatus(1);
            }else {
                bookingScheduleRuleVo.setStatus(0);
            }
            //当天预约如果停号 不能预约
            if(i ==0&& page==1){
                DateTime shopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if (shopTime.isBeforeNow()){
                    //停止预约
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            //设置值
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }
        //可预约的规则数
        map.put("bookingScheduleList",bookingScheduleRuleVoList);
        map.put("total",iPage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname",hospitalService.getHospName(hoscode));
        //科室
        Department department = departmentService.getDepartment(hoscode, depcode);
        //大科室
        baseMap.put("bigname",department.getBigname());
        //科室名称
        baseMap.put("depname",department.getDepname());
        //月
        baseMap.put("workDateString",new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime",bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime",bookingRule.getStopTime());

        map.put("baseMap",baseMap);

        return map ;
    }

    /**
     * 根据排班id获取排班数据
     * @author zyf
     * @date 2021/5/31 14:02
     * @param scheduleId 排班id
     * @return com.zyf.model.hosp.Schedule
     */
    @Override
    public Schedule getScheduleById(String scheduleId) {
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        return this.packageSchedule(schedule);
    }

    /**
     * 根据排班id，获取预约挂号下单数据
     * @author zyf
     * @date 2021/5/31 15:03
     * @param scheduleId 排班id
     * @return com.zyf.vo.hosp.ScheduleOrderVo
     */
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        //获取排班信息
        Schedule schedule = this.getScheduleById(scheduleId);
        if (null == schedule){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //获取医院信息
        Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
        if (null == hospital){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //获取排班信息
        BookingRule bookingRule = hospital.getBookingRule();
        if (null == bookingRule){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //把获取的数据设置到scheduleOrderVo中
        scheduleOrderVo.setHoscode(schedule.getHoscode())
                        .setHosname(hospitalService.getHospName(schedule.getHoscode()))
                        .setDepcode(schedule.getDepcode())
                        .setDepname(departmentService.getDeptName(schedule.getHoscode(), schedule.getDepcode()))
                        .setHosScheduleId(schedule.getHosScheduleId())
                        .setAvailableNumber(schedule.getAvailableNumber())
                        .setTitle(schedule.getDocname()+schedule.getTitle())
                        .setReserveDate(schedule.getWorkDate())
                        .setReserveTime(schedule.getWorkTime())
                        .setAmount(schedule.getAmount());

        //退号截至天数 （就诊的前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime dateTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setQuitTime(dateTime.toDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约结束时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());

        return scheduleOrderVo;
    }

    /**
     * 更新排班数量 用于Mq
     * @author zyf
     * @date 2021/5/31 18:03
     * @param schedule 排班实体
     */
    @Override
    public void updateSchedule(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
    }

    /**
     * 获取可预约分页数据
     * @author zyf
     * @date 2021/5/29 13:50
     * @param page 当前页
     * @param limit 每页记录数
     * @param bookingRule 挂号信息
     * @return com.baomidou.mybatisplus.core.metadata.IPage
     */
    private IPage getListDate(Integer page, Integer limit, BookingRule bookingRule) {
        //获取当前放号的时间   年月日 小时 分
        DateTime releaseTime  = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        //获取预约周期
        Integer cycle = bookingRule.getCycle();
        //如果当前时间已经过去了，预约周期从下一天开始
        if (releaseTime.isBeforeNow()){
            cycle+=1;
        }
        //获取可预约所有日志，最后一天显示即将放号
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            DateTime curDateTime = new DateTime().plusDays(i);
            String dataString = curDateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dataString).toDate());
        }
        //因为预约周期不同，每页显示日期最多7天的数据，超过7天的分页
        List<Date> pageDateList = new ArrayList<>();
        int start = (page-1)*limit;
        int end = (page-1)*limit+limit;

        //如果我们显示的数据小于7 直接显示
        if(end>dateList.size()){
            end = dateList.size();
        }
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }
        //，如果大于7进行分页
        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page,7,dateList.size());
        iPage.setRecords(pageDateList);
        return iPage;

    }

    /**
     * 将日期转换为（yyyy-MM-dd HH:mm）
     * @author zyf
     * @date 2021/5/29 13:54
     * @param date 当前时间
     * @param timeString 小时 分
     * @return org.joda.time.DateTime
     */
    private DateTime getDateTime(Date date,String timeString){

        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd")+" "+timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }

    /**
     * 根据Schedule 封装其他参数
     * @author zyf
     * @date 2021/5/14 14:24
     * @param schedule 排班实体类
     */
    private Schedule packageSchedule(Schedule schedule) {
        //得到医院名称
        String hospName = hospitalService.getHospName(schedule.getHoscode());
        //得到科室名称
        String deptName = departmentService.getDeptName(schedule.getHoscode(),schedule.getDepcode());
        //设置日期对应星期
        String dayOfWeek = this.getDayOfWeek(new DateTime(schedule.getWorkDate()));

        schedule.getParam().put("hospName",hospName);
        schedule.getParam().put("deptName",deptName);
        schedule.getParam().put("dayOfWeek",dayOfWeek);
        return schedule;
    }

    /**
     * 根据日期转换为星期显示
     * @author zyf
     * @date 2021/5/14 9:59
     * @param dateTime
     * @return java.lang.String
     */
    private String getDayOfWeek(DateTime dateTime){
        String dayOfWeek = "";

        switch (dateTime.getDayOfWeek()){

            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
                break;
        }
        return dayOfWeek;
    }
}
